package com.spzx.order.receiver;

import com.rabbitmq.client.Channel;
import com.spzx.common.rabbit.constant.MqConst;
import com.spzx.order.service.IOrderInfoService;
import lombok.SneakyThrows;
import lombok.extern.log4j.Log4j;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @author: L29
 * @create: 2024-11-18 13:15
 * @Version 1.0
 */
@Component
@Slf4j
public class OrderReceiver {
	@Autowired
	private IOrderInfoService orderInfoService;
	@Autowired
	private RedisTemplate redisTemplate;

	@RabbitListener(queues = MqConst.EXCHANGE_CANCEL_ORDER)
	@SneakyThrows
	// TODO 1.处理订单消息
	public void handleOrderMessage(String orderId, Message message, Channel channel) {
		log.info("handleOrderMessage收到消息{}", message);

		// 处理订单消息的逻辑
		if (orderId != null) {
			// 加锁
			String key = "close:lock:" + orderId;
			boolean isSetSuccess = redisTemplate.opsForValue().setIfAbsent(key, orderId, 10, TimeUnit.SECONDS);
			if (!isSetSuccess) {
				log.info("handleOrderMessage重复消费，已经被处理了");
				return;
			} else {
				log.info("handleOrderMessage处理订单消息{}", orderId);
				try {
					// 取消订单
					orderInfoService.processCancelOrder(orderId);
				} catch (Exception e) {
					log.error("handleOrderMessage处理订单消息失败{}", orderId);
				} finally {
					// 解锁
					redisTemplate.delete(key);
				}
			}


		}

		channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
	}
}